<!DOCTYPE html>
<html lang="en">

<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>Document</title>
    <style>
        body {
            margin: 0;
            padding: 30px;
        }

        a {
            text-decoration: none;
        }

        table,
        th,
        td {
            margin-top: 20px;
            border: 1px solid #000;
            /* 设置边框重合 */
            border-collapse: collapse;
            border-spacing: 0px;

        }

        th,
        td {
            padding: 10px;
        }
    </style>
    <!-- 本地导入 -->
    <script src="./node_modules/axios/dist/axios.min.js"></script>
</head>

<body>
    <h1>用户列表</h1>
    <a href="./add.html">添加用户</a>
    <table>
        <thead>
            <tr>
                <th>ID</th>
                <th>用户名</th>
                <th>密码</th>
                <th>操作</th>
            </tr>
        </thead>

        <tbody>
            <tr>
            </tr>
        </tbody>
    </table>
    <script>
        // 1. 获取元素
        const tbody = document.querySelector('tbody')
        // 1. 发送请求
        axios.get('http://localhost:3000/users').then(res => {
            console.log(res)
            // 获取用户数组
            const arr = res.data
            console.log(arr)
            // 遍历数组
            tbody.innerHTML = arr.map(item => {
                return `
                <tr>
                    <td>${item.id}</td>
                    <td>${item.username}</td>
                    <td>${item.password}</td>
                    <td>
                        <a href="./edit.html?id=${item.id}">编辑</a>
                        <a href="" onclick='deleteItem(${item.id})'>删除</a>
                    </td> `
            }).join('')

        })
        // 实现删除的方法
        function deleteItem(id){
            const flag=confirm('确定删除吗？')
            if(flag){
                axios.delete(`http://localhost:3000/users/${id}`).then(res=>{
                    alert('删除成功')
                });
            }
        }
        // // 异步删除
        // function del() {
        //     return new Promise((resolve, reject) => {
        //         // 获取删除
        //         const deleteBtn = document.querySelectorAll('.delete')
        //         console.log(deleteBtn)
        //         deleteBtn.forEach(deleteBtn => {
        //         deleteBtn.addEventListener('click', function (e) {
        //             e.preventDefault()
        //             // 获取id
        //             const id = this.parentNode.parentNode.firstElementChild.innerHTML
        //             // 发送请求
        //             axios({
        //                 url: `http://localhost:3000/users/${id}`,
        //                 method: 'delete'
        //             })})})

        //     })
        // }
        // del()




    </script>
</body>

</html>